<?php

namespace app\api\model;

use think\Db;
use think\Model;

/**
 * 分类模型
 */
class UserShop extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'update_time';
    // 追加属性
    protected $append = [

    ];

    /**
     * @param $ids 分类ID
     * @param string $name
     * @param int $lat  // 纬度
     * @param int $lng // 经度
     */
    public function getShop($ids, $name = '', $lat = '', $lng = '')
    {
        if (!$lat)
        {
            $lat = 0;
        }
        if (!$lng)
        {
            $lng = 0;
        }

        $where = [];
        $where['blackwitch']   = ['eq',0];
        $where['status']       = ['eq',1];
    
        $categoryId = [];

        $p_id = Db::name('goods_category')->field('pid')->where('id','in',$ids)->select();
        $service_type = '';
        foreach($p_id as $val)
        {
            $Id = Db::name('goods_category')->where('id',$val['pid'])->value('pid');

            if (!in_array($Id,$categoryId))
            {

                $categoryId[] = $Id;
                $service_type .= "FIND_IN_SET($Id, service_type) OR ";
            }
        }
        if ($service_type)
        {
            $service_type = rtrim($service_type,' OR ');
        }

        $data = Db::name('user_shop')
            ->field("id,shop_name,order_sum,credit_score,phone,logimage,service_type,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - ".$lat." * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(".$lat." * pi() / 180) * pow(sin((lng * pi() / 180 - ".$lng." * pi() / 180) / 2),2))) * 1000) as distance")
            ->where($where)
            ->where($service_type)
            ->order('distance asc')
            ->select();
        return $data;
    }


    /**
     *安装店详情
     * @param id 安装店id
     * @param userlng 当前经度
     * @param userlat 当前纬度
     * @param uid 用户id
     */
    public function Getshopinfo($id = '', $userlng, $userlat, $uid = '')
    {
        $result = [
            'status' => false,
            'data'   => [
                'list'     => [],  // 商品详情
                'category' => [] , // 服务类型
                'comment'  => []   // 评论
            ],
            'msg'    => '没有该店铺' // 默认
        ];
         $decimal = 2;
         $EARTH_RADIUS = 6370.996; //地球半径
         $res = Db::name('user_shop')->field('user_name, uid, price_sum, trading_sum,goods_num,weigh,status,opinion,audit_time,blackwitch,',true)
            ->where('id',$id)
            ->where('blackwitch',0)
            ->where('status',1)
            ->find();
         if (!$res) return $result;

        /**
         *
         * 获取当前位置到指定位置的距离（Km/公里）精确到2位小数
         * $userlng; 当前位置经纬度
         * $res; 目的地经纬度
         */
        $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin( ($userlng*pi()/180-$res['lng']*pi()/180)/2),2)+cos($userlng*pi()/180)*cos($res['lng']*pi()/180)* pow(sin( ($userlat*pi()/180-$res['lat']*pi()/180)/2),2)))*1000;
        if (!$distance)
        {
            $distance = 0;
        }
        $distance = $distance / 100;

        $res['distance'] = round($distance, 2);

         if ($res['shop_images'])
         {
             $res['shop_images'] = explode(',',$res['shop_images']);
         }
         $service_type = explode(',', $res['service_type']);
         $category = [];
         foreach ($service_type as $item) {
            $category_name = Db::name('goods_category')
                            ->field('id,name')
                            ->where('status',0)
                            ->where('id',$item)
                            ->find();
            if ($category_name)
            {
                $category[] = $category_name;
            }
         }

         $result['data']['list'] = $res;
         $result['data']['category'] = $category;


         $where = [];
         $where['gid'] = ['eq',$id];
         $where['goods_type'] = 'shop';

         if (!$uid)
         {
             $where['status'] = ['eq',0];
         }

         $goods_comment = Db::name('goods_comment')
             ->field('id,uid,content,create_time,status,name,user_image,score,image')
             ->where($where)
             ->order('id desc')
             ->select();
         $comment = [];
         if ($uid){
                foreach($goods_comment as $key => $val)
                {
                    if ($val['status'] == 1 && $val['uid'] != $uid)
                    {
                        continue;
                    }
                    $comment[] = $val;
                }
         }

        $result['status'] = true;
         $result['data']['total'] = count($goods_comment);
        $result['data']['comment']   = $comment;
        $result['msg']    = '获取成功';
        return $result;
    }


    /**
     * 安装店列表
     * @param string $uid 用户id
     * @param $userlat  用户纬度
     * @param $userlng 用户经度
     * @param string $like 搜索=名称
     * @param int $limit 条数
     * @param int $page 页数
     * @param string $category 分类
     */
    public function Shoplist($uid = 0, $userlat, $userlng, $like = '', $limit = 20, $page = 1, $category = '', $distance = '')
    {
//            判断有没有登陆或者没有绑定车型,就根据用户距离显示附近的安装店
//            绑定车型的就,根据车型厂牌查出对应的安装店,并显示.
            $cartype = Db::name('user')->where('id',$uid)->value('cartype'); //找到绑定的车型id

            $where = [];
            $where['status'] = ['eq', 1];
            $label = '';

            // 判断是否绑定车
            if ($cartype)
            {
                // 绑定的话就找到,该车型id,和名称
                 $brand = Db::name('user_car')
                     ->alias('c')
                     ->field('v.id,v.mergename')
                     ->join('vehicle v', 'v.id = c.brand', 'LEFT')
                     ->where('c.id',$cartype)
                     ->find();

                 if (!empty($brand))
                 {
                     $label ="FIND_IN_SET('".$brand['id']."',service_models)";
                 }
            }


            if (!empty($like))
            {
                $where['shop_name'] = ['like','%'.$like.'%'];
            }
            if (!empty($category))
            {
                $category = "FIND_IN_SET('".$category."',service_type)";
            }
            $order ='order_sum asc' ; // 销量排序
            if ($distance)
            {
                $order ='distance asc' ; // 销量排序
            }

            $field_lat = "lat"; //数据库纬度
            $field_lng = "lng"; //数据库经度
            $field = 'id,shop_name,order_sum,credit_score,blackwitch,create_time,address,phone,shop_images,service_type,lng,lat,logimage,service_models';
            $where['blackwitch'] = ['neq',1];
            $kasklas =Db::name('user_shop')
                ->field("{$field}, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$userlat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$userlat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$userlng} * pi() / 180) / 2),2))) * 1000) as distance")
                ->where($where)
                ->where($label)
                ->where($category)
                ->order($order)
                ->select();

            if (!$kasklas)
            { // 没有此车型,显示其他修车店
                $kasklas =Db::name('user_shop')
                    ->field("{$field}, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$userlat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$userlat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$userlng} * pi() / 180) / 2),2))) * 1000) as distance")
                    ->where($where)
                    ->where($category)
                    ->order($order)
                    ->select();
                if (!$kasklas)
                {
                    // 显示所有店铺
                    $kasklas =Db::name('user_shop')
                        ->field("{$field}, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$userlat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$userlat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$userlng} * pi() / 180) / 2),2))) * 1000) as distance")
                        ->where($where)
                        ->order($order)
                        ->select();
                }
            }

            return $kasklas;
    }


}
